<template>
	<div class="box">
		<div class="contentBox" ref="scrollBox" @scroll="handleScroll">
			<div class="box2" :style="heightAdd"></div>
			<ul class="showList" :style="heightReduce">
				<li v-for="(item,idx) in showData" :key="idx">
					<div>{{item.name}}</div>
					<div class="rightBox">
						<input class="text" v-model="item.num" type="text" />
						<input value="x" class="removeBtn" type="button" @click="ev_remove(item)" />
					</div>
				</li>
			</ul>
		</div>

	</div>
</template>

<script>
	export default {
		data() {
			return {
				cartData: [],
				showData: [],
				heightAdd: {},
				heightReduce: {},
				currentIndex:0
			}
		},
		created() {
			this.ev_getCartdata()
		},
		
		methods: {
			async ev_getCartdata() {
				await this.axios('/getCartdata').then(res => {
					this.cartData = res.data
					console.log(this.cartData)
					if (this.getScrollHeight() == 0) {
						this.getShowData()
					}
				})
			},
			ev_remove(item){
				var idx=this.showData.indexOf(item)
				this.showData.splice(idx,1)
				var idx2=this.cartData.indexOf(item)
				this.cartData.splice(idx2,1)
				this.getShowData(this.currentIndex)
			},
			getScrollHeight() { //获取当前滚动条的位置
				return document.documentElement.scrollTop
			},
			handleScroll() {
				var scrollTop = this.$refs.scrollBox.scrollTop;
				var index = Math.floor(parseInt(scrollTop) / 20) //获取当前显示元素的下标
				if(index>=9980){
					index=9980
				}
				this.getShowData(index)
				
				this.heightAdd = {
					height: index * 20 + 'px'
				}
				this.heightReduce = {
					height: parseInt(200000 - index * 20) + 'px'
				}
				this.currentIndex=index
				console.log(this.showData)
			},
			getShowData(index) {
				this.showData = []
				if (index) {
					var n = index + 20
					for (var i = index; i < n; i++) {
						this.showData.push(this.cartData[i])
					}
				} else {
					var m = 20
					for (var j = 0; j < m; j++) {
						this.showData.push(this.cartData[j])
					}
				}
			}
		}
	}
</script>

<style scoped="scoped" lang="less">
	.box {
		.contentBox {
			height: 400px;
			width: 600px;
			overflow: hidden;
			overflow-y: scroll;
			margin: 10px auto;
			
			.box2 {
				height: 0;
			}

			ul {
				height: 220000px;
				border-top:1px solid black;
				li {
					height: 20px;
					border: 1px solid black;
					border-top: none;
					display: flex;
					justify-content: space-between;
					.rightBox{
						display: flex;
						justify-content: space-between;
						.removeBtn{
							width: 15px;
							height: 15px;
							margin:2px 0 0 20px;
							font-size: 10px;
						}
						.text{
							width: 80px;
							height: 15px;
						}
					}
				}
			}
		}

	}
</style>
